package com.lyfx.ly.exception;

import com.lyfx.common.exception.BizCodeEnum;
import com.lyfx.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lsy
 * @create 2020-07-11-10:48
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.lyfx.ly.controller")
public class ExceptionControllerAdvice {

    /**
     * 参数校验异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildExction(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{},异常类型：{}",e.getMessage(),e.getClass());
        BindingResult result = e.getBindingResult();
        Map<String,String> map = new HashMap<>();
        result.getFieldErrors().forEach((item)->{
            map.put(item.getField(),item.getDefaultMessage());
        });
        return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(),BizCodeEnum.VAILD_EXCEPTION.getMsg()).put("data",map);
    }

    /**
     * 最大的异常处理
     */
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable){
        log.error("错误", throwable);
        return R.error(BizCodeEnum.UNKNOWN_REASON.getCode(),BizCodeEnum.UNKNOWN_REASON.getMsg());
    }
}
